package com.ruoyi.system.service.impl;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.UserType;
import com.ruoyi.common.enums.VersionType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.system.domain.GwPlatformRights;
import com.ruoyi.system.domain.GwSystemConfig;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.domain.vo.EnterpriseInfoVO;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.domain.GwEnterpriseInfo;
import com.ruoyi.system.service.IGwEnterpriseInfoService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;

/**
 * 企业信息管理Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-05-06
 */
@Service
public class GwEnterpriseInfoServiceImpl extends BaseService implements IGwEnterpriseInfoService
{
    @Resource
    private GwEnterpriseInfoMapper gwEnterpriseInfoMapper;
    @Resource
    private GwPlatformRightsMapper platformRightsMapper;
    @Resource
    private GwSystemConfigMapper systemConfigMapper;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private SysUserRoleMapper userRoleMapper;
    @Resource
    private SysRoleMapper roleMapper;

    private static final String ENTERPRISE_SYSTEM_ROLE_KEY = "enterprise_system_role";
    private static final String ENTERPRISE_ADMIN_APPLET_ROLE_KEY = "enterprise_admin_applet_role";

    private static final String AVATAR = "https://gowork365.com/prod-api/profile/mini/index/enterpriseLogo.png";

    /**
     * 查询企业信息管理
     * 
     * @param id 企业信息管理主键
     * @return 企业信息管理
     */
    @Override
    public GwEnterpriseInfo selectGwEnterpriseInfoById(String id)
    {
        return gwEnterpriseInfoMapper.selectGwEnterpriseInfoById(id);
    }

    /**
     * 查询企业信息管理列表
     * 
     * @param gwEnterpriseInfo 企业信息管理
     * @return 企业信息管理
     */
    @Override
    public List<GwEnterpriseInfo> selectGwEnterpriseInfoList(GwEnterpriseInfo gwEnterpriseInfo)
    {
        return gwEnterpriseInfoMapper.selectGwEnterpriseInfoList(gwEnterpriseInfo);
    }

    /**
     * 新增企业信息管理
     * 
     * @param gwEnterpriseInfo 企业信息管理
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertGwEnterpriseInfo(GwEnterpriseInfo gwEnterpriseInfo)
    {
        gwEnterpriseInfo.setId(IdUtils.fastSimpleUUID());
        gwEnterpriseInfo.setCreateTime(DateUtils.getNowDate());
        gwEnterpriseInfo.setSignOpenId(createCertificationOpenId());
        int num = gwEnterpriseInfoMapper.insertGwEnterpriseInfo(gwEnterpriseInfo);

        //统一登录账号管理，将账号插入sys_user一份
        SysUser sysUser = new SysUser();
        sysUser.setUserType(UserType.ENTERPRISE_USER.getCode());
        sysUser.setPhonenumber(gwEnterpriseInfo.getPhone());
        sysUser.setNickName(gwEnterpriseInfo.getContacts());
        sysUser.setPassword(SecurityUtils.encryptPassword(gwEnterpriseInfo.getPassword()));
        sysUser.setChannelId(gwEnterpriseInfo.getId());
        sysUser.setSignOpenId(createCertificationOpenId());
        sysUser.setAvatar(AVATAR);
        sysUserMapper.insertUser(sysUser);
        //赋PC端角色
        saveSole(ENTERPRISE_SYSTEM_ROLE_KEY,sysUser.getUserId());

        //赋小程序端角色
        saveSole(ENTERPRISE_ADMIN_APPLET_ROLE_KEY,sysUser.getUserId());


        return num;
    }

    private void saveSole(String roleKey,Long userId){
        //赋PC端角色
        SysRole sysRole = new SysRole();
        sysRole.setRoleKey(roleKey);
        List<SysRole> roleList = roleMapper.selectRoleList(sysRole);
        if(!CollectionUtils.isEmpty(roleList)){
            sysRole = roleList.get(0);
            List<SysUserRole> list = new ArrayList<SysUserRole>(1);
            SysUserRole userRole = new SysUserRole();
            userRole.setRoleId(sysRole.getRoleId());
            userRole.setUserId(userId);
            list.add(userRole);
            userRoleMapper.batchUserRole(list);
        }
    }

    /**
     * 修改企业信息管理
     * 
     * @param gwEnterpriseInfo 企业信息管理
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateGwEnterpriseInfo(GwEnterpriseInfo gwEnterpriseInfo)
    {
        gwEnterpriseInfo.setUpdateTime(DateUtils.getNowDate());
        int num = gwEnterpriseInfoMapper.updateGwEnterpriseInfo(gwEnterpriseInfo);
        //同步修改sys_user 账号信息
        SysUser sysUser = sysUserMapper.selectUserByChannelId(gwEnterpriseInfo.getId());
        if(sysUser!=null){
            sysUser.setPhonenumber(gwEnterpriseInfo.getPhone());
            sysUser.setNickName(gwEnterpriseInfo.getContacts());
            if(!StringUtils.isEmpty(gwEnterpriseInfo.getPassword())){
                sysUser.setPassword(SecurityUtils.encryptPassword(gwEnterpriseInfo.getPassword()));
            }
            sysUserMapper.updateUser(sysUser);
        }
        return num;
    }

    /**
     * 批量删除企业信息管理
     * 
     * @param ids 需要删除的企业信息管理主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteGwEnterpriseInfoByIds(String[] ids)
    {
        int num = gwEnterpriseInfoMapper.deleteGwEnterpriseInfoByIds(ids);
        for(String id:ids){
            SysUser sysUser  = sysUserMapper.selectUserByChannelId(id);
            if(sysUser!=null){
                sysUserMapper.deleteUserById(sysUser.getUserId());
            }
        }
        return num;
    }

    /**
     * 删除企业信息管理信息
     * 
     * @param id 企业信息管理主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteGwEnterpriseInfoById(String id)
    {
        int num = gwEnterpriseInfoMapper.deleteGwEnterpriseInfoById(id);;
        SysUser sysUser  = sysUserMapper.selectUserByChannelId(id);
        if(sysUser!=null){
            sysUserMapper.deleteUserById(sysUser.getUserId());
        }

        return num;
    }

    @Override
    public List<EnterpriseInfoVO> enterpriseInfoList(GwEnterpriseInfo gwEnterpriseInfo) {
        return gwEnterpriseInfoMapper.enterpriseInfoList(gwEnterpriseInfo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult addEnterpriseInfo(GwEnterpriseInfo gwEnterpriseInfo) {
        //校验该手机号是否已注册过，不可重复注册
        if(!checkPhone(gwEnterpriseInfo.getPhone())){
            return AjaxResult.error("该手机号是否已注册过，不可重复注册");
        }
        gwEnterpriseInfo.setId(IdUtils.fastSimpleUUID());
        gwEnterpriseInfo.setCreateBy(SecurityUtils.getUserId()+"");
        gwEnterpriseInfo.setCreateTime(DateUtils.getNowDate());
        gwEnterpriseInfo.setUpdateBy(SecurityUtils.getUserId()+"");
        gwEnterpriseInfo.setUpdateTime(DateUtils.getNowDate());
        gwEnterpriseInfo.setSignOpenId(createCertificationOpenId());
        //如果使用版本为试用版，通过试用天数计算有效期
        if(gwEnterpriseInfo.getVersionType().equals(VersionType.TRIAL_VERSION.getCode())){
            gwEnterpriseInfo.setEffectiveTime(addDaysAndSetToEndOfDay(gwEnterpriseInfo.getTryDays()));
        }else{
            //如果使用版本为正式版，通过套餐计算有效期
            GwPlatformRights platformRights = platformRightsMapper.selectGwPlatformRightsById(gwEnterpriseInfo.getRightsId());
            if(platformRights!=null && platformRights.getAmount()!=null){
                gwEnterpriseInfo.setEffectiveTime(addDaysAndSetToEndOfDay(platformRights.getAmount()));
            }
        }

         gwEnterpriseInfoMapper.insertGwEnterpriseInfo(gwEnterpriseInfo);

        //统一登录账号管理，将账号插入sys_user一份
        SysUser sysUser = new SysUser();
        sysUser.setUserType(UserType.ENTERPRISE_USER.getCode());
        sysUser.setPhonenumber(gwEnterpriseInfo.getPhone());
        sysUser.setNickName(gwEnterpriseInfo.getContacts());
        sysUser.setPassword(SecurityUtils.encryptPassword(gwEnterpriseInfo.getPassword()));
        sysUser.setChannelId(gwEnterpriseInfo.getId());
        sysUser.setSignOpenId(createCertificationOpenId());
        sysUser.setAvatar(AVATAR);
        sysUserMapper.insertUser(sysUser);

        //赋PC端角色
        saveSole(ENTERPRISE_SYSTEM_ROLE_KEY,sysUser.getUserId());

        //赋小程序端角色
        saveSole(ENTERPRISE_ADMIN_APPLET_ROLE_KEY,sysUser.getUserId());


        return AjaxResult.success();
    }

    @Override
    public String enterpriseRegister(GwEnterpriseInfo gwEnterpriseInfo) {
        //校验该手机号是否已注册过，不可重复注册
        if(!checkPhone(gwEnterpriseInfo.getPhone())){
            return "该手机号是否已注册过，不可重复注册";
        }
        gwEnterpriseInfo.setId(IdUtils.fastSimpleUUID());
        gwEnterpriseInfo.setCreateTime(DateUtils.getNowDate());
        gwEnterpriseInfo.setVersionType(VersionType.TRIAL_VERSION.getCode());
        gwEnterpriseInfo.setUpdateTime(DateUtils.getNowDate());
        gwEnterpriseInfo.setSignOpenId(createCertificationOpenId());

        //查询系统配置
        List<GwSystemConfig> configList = systemConfigMapper.selectGwSystemConfigList(new GwSystemConfig());
        if(!CollectionUtils.isEmpty(configList)){
            GwSystemConfig config = configList.get(0);
            gwEnterpriseInfo.setTryDays(config.getTryDays());
            gwEnterpriseInfo.setEffectiveTime(addDaysAndSetToEndOfDay(config.getTryDays()));
        }

        gwEnterpriseInfoMapper.insertGwEnterpriseInfo(gwEnterpriseInfo);

        //统一登录账号管理，将账号插入sys_user一份
        SysUser sysUser = new SysUser();
        sysUser.setUserType(UserType.ENTERPRISE_USER.getCode());
        sysUser.setPhonenumber(gwEnterpriseInfo.getPhone());
        sysUser.setNickName(gwEnterpriseInfo.getContacts());
        sysUser.setPassword(SecurityUtils.encryptPassword(gwEnterpriseInfo.getPassword()));
        sysUser.setChannelId(gwEnterpriseInfo.getId());
        sysUser.setSignOpenId(createCertificationOpenId());
        sysUser.setAvatar(AVATAR);
        sysUserMapper.insertUser(sysUser);

        //赋PC端角色
        saveSole(ENTERPRISE_SYSTEM_ROLE_KEY,sysUser.getUserId());

        //赋小程序端角色
        saveSole(ENTERPRISE_ADMIN_APPLET_ROLE_KEY,sysUser.getUserId());


        return "";
    }


    @Override
    public AjaxResult editEnterpriseInfo(GwEnterpriseInfo gwEnterpriseInfo) {
        gwEnterpriseInfo.setUpdateTime(DateUtils.getNowDate());
        gwEnterpriseInfo.setUpdateBy(SecurityUtils.getUserId()+"");
        //如果使用版本为试用版，通过试用天数计算有效期
//        if(gwEnterpriseInfo.getVersionType().equals(VersionType.TRIAL_VERSION.getCode())){
//            gwEnterpriseInfo.setEffectiveTime(addDaysAndSetToEndOfDay(gwEnterpriseInfo.getTryDays()));
//        }else{
//            //如果使用版本为正式版，通过套餐计算有效期
//            GwPlatformRights platformRights = platformRightsMapper.selectGwPlatformRightsById(gwEnterpriseInfo.getRightsId());
//            if(platformRights!=null && platformRights.getAmount()!=null){
//                gwEnterpriseInfo.setEffectiveTime(addDaysAndSetToEndOfDay(platformRights.getAmount()));
//            }
//        }
        gwEnterpriseInfoMapper.updateGwEnterpriseInfo(gwEnterpriseInfo);

        //同步修改sys_user 账号信息
        SysUser sysUser = sysUserMapper.selectUserByChannelId(gwEnterpriseInfo.getId());
        if(sysUser!=null){
            sysUser.setPhonenumber(gwEnterpriseInfo.getPhone());
            sysUser.setNickName(gwEnterpriseInfo.getContacts());
            sysUser.setPassword(SecurityUtils.encryptPassword(gwEnterpriseInfo.getPassword()));
            sysUserMapper.updateUser(sysUser);
        }

        return AjaxResult.success();
    }

    @Override
    public GwEnterpriseInfo getMyEnterpriseInfo() {
        String enterpriseId = SecurityUtils.getLoginUser().getEnterpriseId();
        if(StringUtils.isEmpty(enterpriseId)){
            return null;
        }
        GwEnterpriseInfo gwEnterpriseInfo =  gwEnterpriseInfoMapper.selectGwEnterpriseInfoById(enterpriseId);
        gwEnterpriseInfo.setContacts(SecurityUtils.getLoginUser().getUser().getNickName());
        return gwEnterpriseInfo;
    }

    @Override
    public AjaxResult getLoginEnterpriseInfo() {

        String enterpriseId = SecurityUtils.getLoginUser().getEnterpriseId();
        if(StringUtils.isEmpty(enterpriseId)){
            return AjaxResult.error("当前登录人未关联任何企业！");
        }


        EnterpriseInfoVO enterpriseInfoVO = gwEnterpriseInfoMapper.getLoginEnterpriseInfo(enterpriseId);
        return AjaxResult.success(enterpriseInfoVO);
    }


}
